package com.scau.jansing.thread.first.resource;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * volatile确保了可视性，
 * 如果一个域是volatile的，那么对它的写操作，都会立刻刷新到主存中。读操作是读主存的内容。
 * 使用volatile并不能解决并发问题。它只能保证每次使用变量时都是最新的，而仍然可以存在多个线程同时操作这个变量
 * http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html
 * Created by jansing on 2015/12/2.
 */
public class LearnVolatile implements Runnable {
    private static int number = 0;
    private int id;

    public LearnVolatile(int id){
        this.id = id;
    }

    @Override
    public void run() {
//        for(int i=0; i<10; i++) {
        try {
//            next();
            System.out.println(id + ", next = " + next());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        }
    }

    public synchronized static int next() throws InterruptedException {
//        Thread.yield();
        Thread.sleep(1);
        number++;
//        Thread.yield();
        return number;
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        for(int i=0; i<1000; i++){
            exec.execute(new LearnVolatile(i));
        }
        Thread.sleep(3000);
        System.out.println(number);
    }

}
